"""
@Author  : 康帅
@Time    : 2021/3/11 13:44
@Function: 抽象出状态模式的框架模型
"""

# 引入ABCMeta，abstractmethod来定义抽象类和抽象方法
from abc import ABCMeta, abstractmethod


class Context(metaclass=ABCMeta):
    """ 状态模式的上下文环境 """

    def __init__(self):
        self.__states = []
        self.__cur_state = None
        # 状态发生变化的依赖属性，当这一变量由多个变量共同决定时可以将其定义成一个类
        self.state_info = 0

    def add_state(self, state):
        """ 添加状态 """

        if state not in self.__states:
            self.__states.append(state)

    def change_state(self, state):
        """ 改变状态 """

        if state is None:
            return False
        if self.__cur_state is None:
            print("初始化为：", state.get_name())
        else:
            print("由", self.__cur_state.get_name(), "变为", state.get_name())
        self.__cur_state = state
        self.add_state(state)
        return True

    def get_state(self):
        """ 获取状态 """

        return self.__cur_state

    def _set_state_info(self, state_info):
        self.__state_info = state_info
        for state in self.__states:
            if state.is_match(state_info):
                self.change_state(state)

    def _get_state_info(self):
        return self.__state_info


class State:
    """ 状态基类(负责状态的定义和接口的统一) """

    def __init__(self, name):
        self.__name = name

    def get_name(self):
        return self.__name

    def is_match(self, state_info):
        """ 状态的属性state_info是否在当前状态的范围"""
        return False

    @abstractmethod
    def behavior(self, context):
        pass
